﻿using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.Extensions.DependencyInjection;

namespace EWms.Core.Components;

public static class CorsSetup
{
    /// <summary>
    /// 添加默认跨域配置
    /// </summary>
    /// <param name="services"></param>
    /// <param name="setupAction"></param>
    /// <returns></returns>
    public static IServiceCollection AddCorsSetup(this IServiceCollection services, Action<CorsOptions>? setupAction = null)
    {
        //提示没有AddCors方法，安装Microsoft.AspNetCore.Mvc.NewtonsoftJson即可
        services.AddCors(options =>
        {
            //添加默认策略
            options.AddDefaultPolicy(policy =>
            {
                if (AppSettings.AllowCors.Any(c => c == "*"))
                {
                    // 允许任意跨域
                    policy.AllowAnyOrigin()
                          .AllowAnyHeader()
                          .AllowAnyMethod();
                }
                else
                {
                    // 允许指定域名
                    policy.WithOrigins(AppSettings.AllowCors);
                }
            });
        });

        // 自定义策略
        if (setupAction != null)
        {
            services.Configure<CorsOptions>(setupAction);
        }

        return services;
    }
}
